const certbot = require('certbot-express');
const cloudflare = require('cloudflare')({ token: 'your-cloudflare-api-token' });
const cron = require('node-cron');

// 获取免费 HTTPS 证书
async function getHttpsCertificate(domain) {
    try {
        const result = await certbot({
            email: 'your-email@example.com',
            domains: [domain],
            agreeTos: true,
            webrootPath: '/var/www/certbot'
        });
        console.log('HTTPS certificate obtained:', result);
        return result;
    } catch (error) {
        console.error('Error obtaining HTTPS certificate:', error);
    }
}

// 自动解析域名（使用 CNAME 记录）
async function updateDnsRecord(domain, target) {
    try {
        const zone = await cloudflare.zones.browse();
        const zoneId = zone.result.find(z => domain.endsWith(z.name)).id;
        const result = await cloudflare.dnsRecords.add(zoneId, {
            type: 'CNAME',
            name: domain,
            content: target,
            ttl: 120
        });
        console.log('DNS record updated:', result);
        return result;
    } catch (error) {
        console.error('Error updating DNS record:', error);
    }
}

// 自动续期 HTTPS 证书
async function renewHttpsCertificate(domain) {
    try {
        const result = await certbot.renew({
            email: 'your-email@example.com',
            domains: [domain],
            agreeTos: true,
            webrootPath: '/var/www/certbot'
        });
        console.log('HTTPS certificate renewed:', result);
        return result;
    } catch (error) {
        console.error('Error renewing HTTPS certificate:', error);
    }
}

// 主函数
async function main() {
    const domain = 'yourdomain.com'; // 您购买的域名
    const target = 'your-target-domain.com'; // 目标域名，例如您的服务器 IP 或其他 CDN 域名

    await getHttpsCertificate(domain);
    await updateDnsRecord(domain, target);

    // 设置自动续期任务，每天凌晨 2 点执行
    cron.schedule('0 2 * * *', async () => {
        console.log('Running certificate renewal task...');
        await renewHttpsCertificate(domain);
    });
}

main().catch(console.error);
